package com.gict.antifraudback.controller.web.login;

import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.result.ResultEnum;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.DESCode;
import com.gict.antifraudback.utils.NoAuthorization;
import com.gict.antifraudback.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;


    @PostMapping("/wapi/login")
    @NoAuthorization
    public ResultView login(@RequestBody LoginVo loginVo){
        String password = DESCode.encode(loginVo.getPassword());
        String username = loginVo.getUsername();
        User user = userService.login(username, password);
        if (user != null) {
            if (!"[\"admin\"]".equals(user.getRoles())){
                throw new MyException(ResultEnum.CODE_403);
            }

            String accessToken = userService.crateBackToken(user.getId());

            Map<String, String> map = new HashMap<>();
            map.put("accessToken", accessToken);
            return ResultView.ok(map);
        }

        return ResultView.error(ResultEnum.CODE_4);
    }

    @PostMapping("/wapi/logout")
    public ResultView logout(){
        return ResultView.ok();
    }
}
